package com.HuangJiaQing.www.service.impl;

import com.HuangJiaQing.www.dao.BillMapper;
import com.HuangJiaQing.www.dao.OrdersMapper;
import com.HuangJiaQing.www.model.*;
import com.HuangJiaQing.www.service.BillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author HONOR
 * @date 2022/8/6 11:24
 */
@Service
public class BillServiceImpl implements BillService {
    @Autowired
    private BillMapper billMapper;
    @Autowired
    private HttpSession session;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    public void insertBill(Orders orders) {
        orders = ordersMapper.selectByPrimaryKey(orders.getOrdersId());
        /*
         * 如果已经被人接单了就结束
         * */
        if (orders.getIsAccept() > 0) {
            return;
        } else {
            final Orders finalOrders = orders;
            final Courier courier = (Courier) session.getAttribute("courier");
            taskExecutor.execute(new Runnable() {
                public void run() {
                    synchronized (this) {
                        finalOrders.setIsAccept(1);
                        ordersMapper.updateByPrimaryKeySelective(finalOrders);
                        Bill bill = new Bill();
                        bill.setCourierName(courier.getCourierName());
                        bill.setUserName(finalOrders.getUsername());
                        bill.setGoodsId(finalOrders.getGoodsId());
                        bill.setMoney(finalOrders.getMoney());
                        billMapper.insertSelective(bill);
                        return;
                    }
                }
            });

        }

    }

    public void completeBillByCourier(Integer id) {
        Bill bill = new Bill();
        bill.setBillId(id);
        bill.setIsComplete(1);
        billMapper.updateByPrimaryKeySelective(bill);
    }

    public List<Bill> selectBillDisagree() {
        User user = (User) session.getAttribute("user");
        BillExample billExample = new BillExample();
        billExample.createCriteria().andUserNameEqualTo(user.getUsername()).andIsAgreeEqualTo(0);
        List<Bill> bills = billMapper.selectByExampleWithGoods(billExample);
        return bills;
    }

    public void completeBillByUser(Integer id) {
        Bill bill = new Bill();
        bill.setBillId(id);
        bill.setIsAgree(1);
        billMapper.updateByPrimaryKeySelective(bill);
    }
}
